import 'package:bike_ride/api/common_repository.dart';
import 'package:bike_ride/api/login_repository.dart';
import 'package:bike_ride/common/util/sp_utils.dart';
import 'package:bike_ride/main/app.dart';
import 'package:bike_ride/model/login/model/login_m.dart';
import 'package:bike_ride/model/main/model/area_info_m.dart';
import 'package:bike_ride/model/main/model/brand_info_m.dart';
import 'package:bike_ride/model/main/model/user_info_m.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';

class AccountManager {
  AccountManager._();

  static final AccountManager _instance = AccountManager._();

  factory AccountManager() => _instance;

  static UserInfoM? userInfo;
  static BrandInfoM? brandInfo;
  static AreaInfoM? areaInfoM;

  static String baseUrl = 'https://agreement.ebikerun.com';
  static String get privacyProtocolUrl => '$baseUrl/yqcx/privacy.html';
  static String get useProtocolUrl => '$baseUrl/yqcx/user.html';
  static String get payProtocolUrl => brandInfo?.payAgreementUrl ?? '';

  /// 是否首次打开，用于显示欢迎页
  /// true : 首次打开
  static bool? _isFirstOpen;
  static bool get isFirstOpen{
   _isFirstOpen ??= SpUtils.getBool(SpUtilsKey.$isFirstOpen,defValue: true);
    return _isFirstOpen!;
  }
  static void updateIsFirstOpen(bool value) {
    _isFirstOpen = value;
    SpUtils.putBool(SpUtilsKey.$isFirstOpen,value);
  }

  /// 判断登录状态
  static bool get isLogin{
    if(authToken == null || authToken!.isEmpty) return false;
    if(userId == null || userId!.isEmpty) return false;
    // if(parseToInt(loginModel?.expire) < DateTime.now().millisecondsSinceEpoch / 1000) return false; //过期

    return true;
  }
  static String? get authToken => loginModel?.token;
  static String? get userId => loginModel?.userId;
  static LoginM? _loginModel;
  static LoginM? get loginModel{
    if(_loginModel == null){
      final logMapJson = SpUtils.getStringMap(SpUtilsKey.$loginInfo);
      if(logMapJson != null && logMapJson.isNotEmpty){
        _loginModel = LoginM.fromJson(logMapJson);
      }
    }
    return _loginModel;
  }
  static void updateLoginModel(LoginM? model){
    _loginModel = model;
    SpUtils.putStringMap(SpUtilsKey.$loginInfo,model?.toJson()??{});
  }

  ///用户当前位置
  static double? _userLatitude;
  static double? _userLongitude;
  static double? get userLatitude {
    _userLatitude ??= SpUtils.getDouble(SpUtilsKey.$userLatitude,defValue: 23.045090);
    return _userLatitude;
  }
  static double? get userLongitude {
    _userLongitude ??= SpUtils.getDouble(SpUtilsKey.$userLongitude,defValue: 113.397570);
    return _userLongitude;
  }
  static Future updateUserLocation({required double lat,required double lng})async{
    _userLatitude = lat;
    _userLongitude = lng;
    SpUtils.putDouble(SpUtilsKey.$userLongitude,userLongitude!);
    SpUtils.putDouble(SpUtilsKey.$userLatitude,userLatitude!);
  }

  ///品牌code
  /// 默认：yqcx
  /// 印尼：ledayn
  /// 马来：ledaml
  static String? _brandCode;
  static String get brandCode {
    _brandCode ??= SpUtils.getString(SpUtilsKey.$brandCode,defValue: 'yqcx');
    return _brandCode!;
  }
  static Future<bool> updateBrandCode(String? code)async{
    /// 兼容车辆编号不规则 没有code情况返回true
    if(code == null || code.isEmpty)return true;

    if(_brandCode != code){
      final mLoginM = await LoginRepository.changeBrandIdl(newBrandCode: code);//此时还需要用旧品牌信息获取
      if(mLoginM != null){
        updateLoginModel(mLoginM);
        _brandCode = code;
        SpUtils.putString(SpUtilsKey.$brandCode,code);

        //重置品牌信息
        final mBrandInfo = await CommonRepository.getBrandInfoIdl();
        final mUserInfo = await CommonRepository.getUserInfoIdl();
        if(mBrandInfo != null && mUserInfo != null){
          brandInfo = mBrandInfo;
          userInfo = mUserInfo;

          //重置区域code信息
          _bikeAreaCode = null;
          await handleAreaCode(lat: userLatitude,lng: userLongitude,forceRefresh: true);
          return true;
        }else{
          toLogin();
        }
      }
      return false;
    }else{
      return true;
    }
  }

  /// 区域code
  static String? _areaCode;
  //默认取北京code
  static String get areaCode {
    _areaCode ??= SpUtils.getString(SpUtilsKey.$areaCode,defValue: '440113');
    return _areaCode!;
  }
  //当前扫码车辆的区域code，扫码成功后赋值（优先取值）,TODO 重新进入APP获取到进行中的工单场景也需要赋值
  static String? _bikeAreaCode;

  /// [tBikeAreaCode] 传入车辆的区域code
  /// [refreshBrandInfoBol] 是否需要刷新品牌信息
  static Future handleAreaCode({
    double? lat,
    double? lng,
    String? tBikeAreaCode,
    bool refreshBrandInfoBol = true,
    bool forceRefresh = false,
  }) async {
    String mCode = _areaCode.toString();
    if(tBikeAreaCode != null && tBikeAreaCode.isNotEmpty){
      //p1:扫码车辆后根据车辆信息获取areaCode
      _bikeAreaCode = _areaCode = tBikeAreaCode;
      SpUtils.putString(SpUtilsKey.$areaCode,_areaCode);
    }else if(lat != null && lng != null){
      //p2:定位成功后根据经纬度获取附近最近的车辆areaCode
      _areaCode = await CommonRepository.getAreaCodeByNearByBikeIdl(lat: lat,lng: lng);
      if(_areaCode!.isEmpty){
        //p3:定位成功后根据经纬度获取areaCode
        final result = await CommonRepository.getAddressByLgoIdl(lat: lat,lng: lng);
        _areaCode = result?.adcode??'';
      }
      if(_bikeAreaCode == null || _bikeAreaCode!.isEmpty){
        if(_areaCode!.isNotEmpty){
          _bikeAreaCode = _areaCode;
          SpUtils.putString(SpUtilsKey.$areaCode,_areaCode);
        }
      }
    }

    if((refreshBrandInfoBol && mCode != _areaCode) || forceRefresh){
      final result = await CommonRepository.getBrandAreaInfoIdl();
      if (result != null) {
        areaInfoM = result;
      }
    }
  }

  static void handleLogin(LoginM model){
    updateLoginModel(model);
    updateIsFirstOpen(false);
  }

  /// 清除登录信息
  static void handleLogout() {
    userInfo = null;
    updateLoginModel(null);
  }

  ///跳转登录页
  static void toLogin({bool clearStack = true}) {
    handleLogout();
    NavigatorUtil.push(navigatorKey.currentContext!,
        Routers.loginView,clearStack: clearStack
    );
  }
}
